package com.strive.village.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.strive.village.entity.SysMenu;
import com.strive.village.entity.SysRole;
import com.strive.village.entity.SysUser;
import com.strive.village.mapper.SysUserMapper;
import com.strive.village.service.SysMenuService;
import com.strive.village.service.SysRoleService;
import com.strive.village.service.SysUserService;
import com.strive.village.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    //*注入需要的操作方法
    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysMenuService sysMenuService;

    // 权限的缓存 引入redis
    @Autowired
    RedisUtils redisUtils;

    @Override
    public SysUser getByUsername(String username) {
        // 使用mybatis的写法
        return getOne(new QueryWrapper<SysUser>().eq("username", username));
    }

    /**
     * 根据用户ID获取用户权限信息
     * 主要获取了用户的 菜单权限信息和角色权限信息
     */
    @Override
    public String getUserAuthorityInfo(Long userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        String authority = "";
        // 先判断redis中是否缓存了权限信息
        if (redisUtils.hasKey("GrantedAuthority:" + sysUser.getUsername())) {
            authority = (String) redisUtils.get("GrantedAuthority:" + sysUser.getUsername());
        } else {
            // 获取角色信息
            List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id = " + userId));// 条件构造器
            // 如果有多个角色
            if (roles.size() > 0) {
                // 格式转换
                String roleCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
                authority = roleCodes;
            }

            // 获取菜单权限信息 涉及到三个表的查询
            List<Long> menuIds = sysUserMapper.getNavMenuIds(userId);
            if (menuIds.size() > 0) {
                // 根据menuID 继续查库 获取所有的menu
                List<SysMenu> menus = sysMenuService.listByIds(menuIds);
                // 以流的方式获取用户菜单权限数据
                String menuPerms = menus.stream().map(r -> r.getPerms()).collect(Collectors.joining(","));
                // 将菜单数据也添加到权限字符串中
                authority = authority.concat(",").concat(menuPerms);
            }

            // 缓存的关键字： GrantedAuthority+用户名， 缓存的数据是权限信息， 缓存的时间是1小时 （单位是秒）
            redisUtils.set("GrantedAuthority:" + sysUser.getUsername(), authority, 60 * 60);
        }
        return authority;
    }

    @Override
    public void clearUserAuthorityInfo(String username) {
        redisUtils.del("GrantedAuthority:" + username);
    }

    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {
        List<SysUser> users = this.list(new QueryWrapper<SysUser>()
                // 分两步查找，现根据关联表找到角色对应的userId 然后根据UserId查找用户信息
                .inSql("id", "select user_id from sys_user_role where role_id = " + roleId));
        users.forEach(user -> {
            this.clearUserAuthorityInfo(user.getUsername());
        });
    }

    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
        // 根据菜单ID查询到 相关用户列表
        List<SysUser> users = sysUserMapper.listByMenuId(menuId);
        users.forEach(user -> {
            this.clearUserAuthorityInfo(user.getUsername());
        });
    }
}
